#!/usr/bin/env python
# -*- coding:utf-8 -*-

from flask import current_app
from flask import jsonify
from flask import request
import pymongo

from i_manager.background.models_sqlalchemy import Seeds
from . import seed_api as app


@app.route('/delete_seed', methods=['GET'])
def delete_parser_config():
    args = request.args
    session = current_app.config['Dsession']()
    try:
        if not session.query(Seeds).filter_by(id=int(args['id'])).count():
            raise Exception('no this seed')
        session.query(Seeds).filter_by(id=int(args['id'])).delete()
        session.commit()
        return jsonify({'status': True, 'count': 0, 'data': {'id': args['id']}})
    except Exception, e:
        return jsonify({'status': False, 'data': e.message})
    finally:
        if session:
            session.close()


@app.route('/restart_seed', methods=['GET'])
def restart_seed():
    seed_id = request.args.get('seed_id', '')
    site = request.args.get('site', '')
    try:
        if seed_id and site:
            scheduler = current_app.config['scheduler']
            scheduler.restart_seed(seed_id, site)
        else:
            raise Exception('no argument id')
    except Exception, e:
        return jsonify({'code': 500, 'status': False, 'data': e.message, 'count': 0})
    return jsonify({'code': 0, 'status': True, 'count': 1, 'data': ''})


@app.route('/mongodb_test', methods=['GET'])
def mongodb_test():
    host = request.args.get('host', '')
    host = str(host)
    port = request.args.get('port', '')
    port = int(port)
    db = request.args.get('db', '')
    username = request.args.get('username', '')
    password = request.args.get('password', '')
    table = request.args.get('table', '')

    try:
        if host and port:
            conn = pymongo.MongoClient(host=host, port=port)
            if username and password:
                conn[db].authenticate(username, password)

            if db and table:
                col = conn['final_data']['table']
                for record in col.find().limit(1):
                    print record

        else:
            raise Exception('no host or port')
    except Exception, e:
        return jsonify({'code': 500, 'status': False, 'data': e.message, 'count': 0})

    return jsonify({'code': 0, 'status': True, 'count': 1, 'data': ''})
